package com.content.scaffold.common.mybatis;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author luowenliang
 */
@Data
public class SuperQuery implements Serializable {

    public static final String ASC = "asc";

    public static final String DESC = "desc";

    /**
     * 页数，默认为1
     */
    protected Integer page = 1;
    /**
     * 每页大小，默认为10
     */
    protected Integer size = 10;

    /**
     * 排序方式，可选择：desc asc，默认asc
     */
    protected String order = ASC;

    /**
     * 排序字段
     */
    protected String sort;

    /**
     * 多种排序条件，如果order和sort中已经传入参数，则此参数无效
     */
    protected List<OrderItem> orderItems;


    protected Map<String, Object> param = new HashMap<>();

    public SuperQuery addParam(String key, Object value) {
        this.param.put(key, value);
        return this;
    }

    public Page getPageEntity() {
        Page page = new Page<>(this.getPage(), this.getSize());
        if (StringUtils.isNotBlank(this.getSort())) {
            OrderItem orderItem;
            if (SuperQuery.ASC.equals(this.getSort())) {
                orderItem = OrderItem.asc(this.getSort());
            } else {
                orderItem = OrderItem.desc(this.getSort());
            }
            page.addOrder(orderItem);
        } else {
            page.setOrders(this.getOrderItems());
        }
        return page;
    }

    public void setParams() {

        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 设置为可访问
            field.setAccessible(true);
            try {
                Object value = field.get(this);
                addParam(field.getName(),value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
